import { ElMessageBox } from 'element-plus'
import { binMsg } from '@/global/api.js'
import { titleCase } from '@/utils/utils.js'
import { selector2, filterList2 } from '@/utils/cascaderUtil.js'
import {
  searchCourse,
  updateCourseState,
  updateCourseInfo,
  createCourse,
  deleteById
} from '@/services/course.js'
import { findCMC } from '@/services/college.js'
import { searchStudentByTidAndStuName } from '@/services/selectLesson.js'

const lessonManageModule = {
  namespaced: true,
  state() {
    return {
      courseList: [],
      courseCount: 0,
      // 创建课程时选择所属专业的数据
      college_major_options: [],
      // 【教师-选课情况】，列表
      courseCaseList: [],
      courseCaseCount: 0,
      // 【教师-我的学生】，列表
      myStuList: [],
      myStuCount: 0
    }
  },

  mutations: {
    changeCourseList(state, list) {
      state.courseList = list
    },
    changeCourseCount(state, count) {
      state.courseCount = count
    },
    changeCollege_major_options(state, list) {
      state.college_major_options = list
    },
    changeCourseCaseList(state, list) {
      state.courseCaseList = list
    },
    changeCourseCaseCount(state, count) {
      state.courseCaseCount = count
    },
    changeMyStuList(state, list) {
      state.myStuList = list
    },
    changeMyStuCount(state, count) {
      state.myStuCount = count
    },
    // 清空数组数据
    clearState(state) {
      state.courseList = []
      state.college_major_options = []
      state.courseCaseList = []
      state.myStuList = []
    }
  },

  actions: {
    // 获取学院、专业
    async getCollegeAndMajor({ commit }, payload) {
      const { data: res } = await findCMC()
      // 将数据修改成合适的格式交给 selector3 进行嵌套
      const newColleges = res.data.data.collegeRes.map((item) => {
        return { id: item.id, label: item.college_name, value: item.college_name }
      })
      const newMajors = res.data.data.majorRes.map((item) => {
        return { id: item.id, label: item.major_name, value: item.major_name, cid: item.cid }
      })

      const selectorList = selector2({
        oneId: 'id', //第一级id
        twoIds: 'id', //第二级id
        twoId: 'cid', //第二级关联第一级的id
        arrOneData: newColleges, //第一级数据
        arrTwoData: newMajors //第二级数据
      })
      // console.log(selectorList)
      commit('changeCollege_major_options', [...filterList2(selectorList)])
    },

    // 查询页面数据
    async searchAction({ commit, state, dispatch, rootState }, payload) {
      // 如果是教师发送请求，则添加 teacher_id 作为请求参数
      const userInfo = rootState.userModule.userInfo
      if (userInfo.role === 1) {
        payload.teacher_id = userInfo.id
      }
      // console.log('searchAction', payload)
      const { data: res } = await searchCourse(payload)
      if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
      const name = titleCase(payload.pageName)
      commit(`change${name}List`, res.data.list)
      commit(`change${name}Count`, res.data.total)
      if (state.college_major_options.length === 0) {
        dispatch('getCollegeAndMajor')
      }
    },

    // 创建课程
    async createAction({ commit, dispatch, rootState }, payload) {
      // 先获取到其他模块中的state数据（userModule -> state）
      const teacherInfo = rootState.userModule.userInfo
      payload.formData.teacher_id = teacherInfo.id
      payload.formData.teacher_name = teacherInfo.name
      // 处理上课时间和所属专业连级选择器的数据
      payload.formData.time_1 = payload.formData.time_1.split('.')[1]
      payload.formData.time_2 = payload.formData.time_2.split('.')[1]
      if (payload.formData.time_1 === payload.formData.time_2) {
        return binMsg('warning', '注意，两次上课时间不可重复！')
      }
      const arr = payload.formData.major_name.split(',')
      payload.formData.college_name = arr[0]
      payload.formData.major_name = arr[1]
      // console.log(payload)
      const { data: res } = await createCourse(payload)
      if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
      binMsg('success', res.meta.msg)
      dispatch('searchAction', {
        pageName: payload.pageName,
        label: 'course_name',
        value: '',
        page_num: 1,
        page_size: 10,
        teacher_id: teacherInfo.id
      })
    },

    // 编辑课程
    async editAction({ commit, state }, payload) {
      payload.formData.time_1 = payload.formData.time_1.split('.')[1]
      payload.formData.time_2 = payload.formData.time_2.split('.')[1]
      // 若修改了专业
      if (payload.formData.major_name.includes(',')) {
        const arr = payload.formData.major_name.split(',')
        payload.formData.college_name = arr[0]
        payload.formData.major_name = arr[1]
      }
      const { data: res } = await updateCourseInfo(payload)
      // console.log(res)
      if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
      // 修改原课程列表数据
      const newCourse = res.data.data
      const newCourseList = [...state.courseList]
      for (let i = 0; i < newCourseList.length; i++) {
        if (newCourseList[i].id === newCourse.id) {
          newCourseList[i] = newCourse
        }
      }
      commit('changeCourseList', newCourseList)
      binMsg('success', res.meta.msg)
    },

    // 删除课程
    async deleteAction({ commit, state }, payload) {
      try {
        await ElMessageBox.confirm('确认删除该课程吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          draggable: true
        })
        // 发送请求进行删除
        const { data: res } = await deleteById(payload.id)
        if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
        const newList = state.courseList.filter((item) => item.id !== payload.id)
        const newCount = state.courseCount - 1
        commit('changeCourseList', newList)
        commit('changeCourseCount', newCount)
        binMsg('success', res.meta.msg)
      } catch (e) {
        binMsg('info', '已取消')
      }
    },

    // 修改课程状态
    async updateStateAction({ commit }, payload) {
      const { data: res } = await updateCourseState(payload.id)
      if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
      binMsg('success', res.meta.msg)
    },

    // 查询选课情况页面数据
    async searchCaseAction({ commit, rootState }, payload) {
      // 如果是教师发送请求，则添加 teacher_id 作为请求参数
      const userInfo = rootState.userModule.userInfo
      if (userInfo.role === 1) {
        payload.teacher_id = userInfo.id
      }
      const { data: res } = await searchCourse(payload)
      if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
      commit(`changeCourseCaseList`, res.data.list)
      commit(`changeCourseCaseCount`, res.data.total)
    },

    // 查询我的学生页面数据
    async searchMyStuAction({ commit, rootState }, payload) {
      const userInfo = rootState.userModule.userInfo
      payload.tid = userInfo.id
      const { data: res } = await searchStudentByTidAndStuName(payload)
      if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
      commit(`changeMyStuList`, res.data.list)
      commit(`changeMyStuCount`, res.data.total)
    }
  },
  getters: {
    pageList(state) {
      return (name) => {
        // 处理上课时间，改成这种形式：【星期一 8:30~10:05】 -> (1).11
        // 原因是：连级选择器只有当最后一级的值相同是，才会将数据回显，再修改课程时使用
        return state[`${name}List`].map((item) => {
          return {
            ...item,
            time_1: `(${String(item.time_1).split('')[0]}).${item.time_1}`,
            time_2: `(${String(item.time_2).split('')[0]}).${item.time_2}`
          }
        })
      }
    },
    pageCount(state) {
      return (name) => {
        return state[`${name}Count`]
      }
    }
  }
}

export default lessonManageModule
